package com.ruizhong.centercontroll.util;

import com.fazecast.jSerialComm.SerialPort;

import java.io.IOException;


public class RS485Util {

    public static void send(Integer serialNumber, byte[] message,Integer baudRate,Integer dataBits,Integer stopBits,Integer parityBits) throws IOException {
        // 获取所有可用的串行端口
        SerialPort[] ports = SerialPort.getCommPorts();
        int aimIndex;
        for (aimIndex = 0; aimIndex < ports.length; aimIndex++) {
            if (ports[aimIndex].getSystemPortName().equals("COM" + serialNumber)) {
                break;
            }
        }
        if (aimIndex == ports.length) {
            throw new RuntimeException("目标串口不存在");
        }
        // 假设我们选择第一个串行端口
        SerialPort serialPort = ports[aimIndex];

        // 打开串行端口
        if (serialPort.openPort()) {
            System.out.println("Port opened successfully.");
        } else {
            System.out.println("Failed to open port.");
            return;
        }

        // 配置串行端口参数（例如波特率、数据位、停止位、校验位）
        serialPort.setComPortParameters(baudRate, dataBits, stopBits, parityBits);
        serialPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING, 1000, 0);

        // 创建输入和输出流
        serialPort.getOutputStream().write(message);
        serialPort.getOutputStream().flush();


        // 关闭串行端口
        serialPort.closePort();
    }

}
